precision mediump float;
uniform vec4 u_color;
uniform vec3 u_light;
uniform sampler2D u_texture;
varying vec2 v_uv;
varying vec3 v_normal;
uniform vec3 u_campos;
varying vec4 v_positionW;

void main()
{
	if (!(u_color.x == 0.0 && u_color.y == 0.0 && u_color.z == 0.0 && u_color.w ==0.0))
	gl_FragColor = u_color;
	else
	{
	gl_FragColor = texture2D(u_texture, v_uv);
	vec3 lightvector = normalize(u_light - v_positionW.xyz);
	float NdotL = dot(v_normal, lightvector);
	//calculate Diffuse
	vec4 diffuse = vec4(vec3(1.0,1.0,1.0) * NdotL, 0.0);
  	vec4 specular = vec4(0.0, 0.0, 0.0, 0.0);
	//calculate Ambient Term
    vec4 ambient = vec4(1.0, 1.0, 1.0, 1.0); 

	//calculate Specular
	if (NdotL > 0.0)
	{
		vec3 E = normalize(u_campos - v_positionW.xyz);	
		vec3 R = normalize(reflect(-lightvector, v_normal));  
		specular = gl_FragColor * pow(max(dot(R,E),0.0),8.0);
	}
	
	// feed into our frag colour
	float weight = 0.5;
	gl_FragColor = vec4(((ambient * weight + diffuse * (1.0 - weight)) * gl_FragColor + specular).xyz, gl_FragColor.w);
	
	//Fog
						  //(maxdist - camdist) / (maxdist - mindist)
	float LerpValue = clamp((10.0 - distance(v_positionW.xyz,u_campos)) / (10.0 - 1.0), 0.0, 1.0);
	gl_FragColor = (1.0 - LerpValue) * vec4(1.0, 1.0, 1.0, 1.0) + (LerpValue) * gl_FragColor;
	
    //gl_FragColor = ambient + diffuse + specular;
	//gl_FragColor.x = float(int(gl_FragColor.x * 255.0 / 40.0)) * 40.0 / 255.0;
	//gl_FragColor.y = float(int(gl_FragColor.y * 255.0 / 40.0)) * 40.0 / 255.0;
	//gl_FragColor.z = float(int(gl_FragColor.z * 255.0 / 40.0)) * 40.0 / 255.0;
	//gl_FragColor.w = float(int(gl_FragColor.w * 255.0 / 40.0)) * 40.0 / 255.0;
     }                 
}
